home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2647 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.0 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: casting virtual base classpointer to derived
  5. Date: 18 Jan 1996 22:29:29 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan18172929@g7240065.bridge.bst.bls.com>
  8. References: <DLE98M.nEI@novice.uwaterloo.ca>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: mkalisia@novice.uwaterloo.ca's message of Thu, 18 Jan 1996
  11.     20:36:22 GMT
  12.  
  13. In article <DLE98M.nEI@novice.uwaterloo.ca> mkalisia@novice.uwaterloo.ca (Maciej Kalisiak) writes:
  14.  
  15. : I ran into a "limitation" of C++ that I wasn't aware off, and I was
  16. : hoping someone out there can tell me how to get around this
  17. : limitation:
  18.  
  19. : I have a base class Base. I derive a number of other classes from Base
  20. : using "virtual public". I have an array/list of Base*, which holds
  21. : pointers to a whole bunch of object of type Base, or any of the derived
  22. : ones. I take one of these pointers (Base*) and I know that it was
  23. : really pointing to a derived class. I try to cast to this derived class
  24. : but I can't (supposedly all compilers are supposed to issue an error in
  25. : such a case).
  26.  
  27. Compilers should not let you assign a Base* to a Derived* but it shouldn't
  28. stop you explicitly casting it to a Derived*, i.e.:
  29.  
  30.   Base* b = new Derived;
  31.   Derived* d = (Derived*)b;
  32.  
  33. Though this is considered an unsafe cast.
  34. The ANSI C++ Standard has introduced RTTI (Run Time Type Information) that
  35. allows you to safely down cast to derived pointers, though few compilers
  36. have actually implemented RTTI yet:
  37.  
  38.   Base* b = new Derived;
  39.   Derived* d = dynamic_cast<Derived*>b;
  40.   if (!d)
  41.       deal with error;
  42.   
  43.  
  44. : Any ideas of how to keep such a list of derived type objets using
  45. : Base*'s, or how to get around this ???
  46.  
  47. Is it absolutely necessary to actually be talking to Derived objects ?
  48. Providing relevent virtual functions in the Base class may be an alternative
  49. solution.
  50.  
  51. Regards
  52.  
  53.    -A.
  54.  
  55. -- 
  56. | A.Champion                |
  57.